package controllers;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import javax.swing.JOptionPane;

import model.FinanceSystemModel;
import model.SubscriptionRequestModel;
import model.UnregisteredUser;
import view.PendingRequestDetailsGUI;
import client.CliMessage;
import client.MailMessage;


		/**
		 * This Class is a Pending Subscription Request Details Controller which extends AbstractController
		 * @author Tal 
		 *
		 */

		public class PendingSubscriptionRequestDetailsController extends AbstractController
		{	
					private PendingRequestDetailsGUI PendingRequestDetailsView;
					private SubscriptionRequestModel subReqModel;
					UnregisteredUser subCus = null;
					/**
					 * This is Pending Subscription Request Details controller constructor.
					 * @param PendingRequestDetailsView is a Pending Request Details Window instance.
					 * @param subReqModel is a Subscription Request Model instance.
					 */
					public PendingSubscriptionRequestDetailsController(PendingRequestDetailsGUI PendingRequestDetailsView, SubscriptionRequestModel subReqModel) 
					{
						super(PendingRequestDetailsView,subReqModel);
						this.PendingRequestDetailsView = PendingRequestDetailsView;
						this.subReqModel = subReqModel;
					}
					/**
					 * This is setButtons method-this method add listeners to buttons in Subscriptions Request Details -approve/deny.
					 * 
					 */
					public void SetButtons(String reqid,SubscriptionRequestModel subReqModel)
					{
						PendingRequestDetailsView.addApproveActionListener(new ApproveListener(reqid,subReqModel,this));
						PendingRequestDetailsView.addDenyActionListener(new DenyListener(reqid,subReqModel));
					}

					/**
					 * This is SendMail method-send mail to customer for his Subscription 
					 * @param String id, boolean-true/false
					 */
					
					public void SendMail(String body,String email)
					{
						MailMessage send = new MailMessage();
						
						
						send.sendMail(email,"Receipt From SGI Finance System ",body);
					}
					
					/**
					 * Inner class that handles when Approve Button Pressed, extends AbstrctListener
					 * @author Tal
					 *
					 */
					
					class ApproveListener extends AbstractListener
					{
						private PendingSubscriptionRequestDetailsController Observer;
						private SubscriptionRequestModel subReqModel;
						private String reqid;
						public ApproveListener(String reqid,SubscriptionRequestModel subReqModel,PendingSubscriptionRequestDetailsController observer)
						{
							this.subReqModel=subReqModel;
							this.reqid=reqid;
							this.Observer=observer;
						}
								
						@Override
						public void actionPerformed(ActionEvent arg0) 
						{
							
						//change Subscription request status in DB to Approved by Customer Service
							String updateQuary = "adu"+ "UPDATE subreq " +
								    					" SET isapprovedbycussrvc = 1 " +
								    					" WHERE reqid = " + reqid;
                    
							//send 
							 sendToServer(updateQuary);
							
							
						
							///Finance System Controller
							 
							 
							//create finance System Model
							FinanceSystemModel finSystemModel=new FinanceSystemModel();
							//init model
							finSystemModel.setUID(subReqModel.getUID());
							finSystemModel.setGID(subReqModel.getGID());
							finSystemModel.setPID(subReqModel.getPID());
							System.out.println("create finance::: "+finSystemModel.getPID()+"  sub pid:::::"+subReqModel.getPID());
							finSystemModel.setCreditN(String.valueOf(subReqModel.getCreditN()));
							finSystemModel.setCCV(subReqModel.getCCV());
							finSystemModel.setExpire(subReqModel.getExpire());
							finSystemModel.setType(subReqModel.getType());
							finSystemModel.setArea(subReqModel.getLocation());
							finSystemModel.setDiscount(false);
							//create controller
							FinanceSystemController finSysCon=new FinanceSystemController(finSystemModel,Observer);
							//set Observer
							setCurrentObserver(finSysCon);
									
						}
					}
					

					/**
					 * Inner class that handles when Deny Button Pressed, implements Action listener
					 * @author Tal
					 *
					 */
					
					class DenyListener implements ActionListener
					{
										
						private SubscriptionRequestModel subReqModel;
						private String reqid;
						public DenyListener(String reqid,SubscriptionRequestModel subReqModel)
						{
							this.subReqModel=subReqModel;
							this.reqid=reqid;
						}
								
						@Override
						public void actionPerformed(ActionEvent arg0) 
						{
							
							//change Subscription request status in DB to Deny by Customer Service
							String updateQuary = "adu"+ "UPDATE subreq " +
								    					" SET isapprovedbycussrvc = 2 " +
								    					" WHERE reqid = " + reqid;

							
							
						
							///get curr subscriptions request
							String searchQuery = "search"	+"SELECT sReq.reqid,sReq.uid,u.fname,u.lname "
			                        +" FROM subreq AS sReq, user AS u"
                                    +" WHERE sReq.uid=u.uid AND sReq.isapprovedbycussrvc=0 ";
                              
							
							//activate the back button
							PendingRequestDetailsView.clickBackButton();
							
							
							 sendToServer(updateQuary);
	                         sendToServer(searchQuery);
										
						}
					}


					@Override
					public void handleDBRequestSuccess()
					{
						PendingRequestDetailsView.displayWrnMessage("Request Details:");
						
                       
						
					}
					
					@Override
					public void handleDBSearchResult(CliMessage dbResult) 
					{	
						//get Details tupple
						ArrayList<HashMap<String, String>> srs = dbResult.getSrs();
						
						 
						//invoice check up
					  if(srs.get(0).get("INVOICE_NUMBER")==null)
						{	
						   String reqid=null;
						   int rows=srs.size();
                          
                     
						  for(int i = 0 ; i <rows  ; i++)
						  {
						   Map<String, String> RequestTupple  = srs.get(i);	
							    	
						   System.out.println("user id:"+RequestTupple.get("UID")+" "+"group id :"+RequestTupple.get("GID")+" "+"creditNum:"+RequestTupple.get("CREDITNUM")+" "+"ccv:"+RequestTupple.get("CCV")+" "+"expire:"+RequestTupple.get("EXPIRE"));
						 //initialzie SubscriptionRequest
						   reqid=RequestTupple.get("REQID");
						   subReqModel.setUID(Integer.valueOf(RequestTupple.get("UID")));
						   subReqModel.setGID(Integer.valueOf(RequestTupple.get("GID")));
						   subReqModel.setPID(Integer.valueOf(RequestTupple.get("PID")));
						   subReqModel.setCreditN(Long.valueOf(RequestTupple.get("CREDITNUM")));
						   subReqModel.setCCV(Integer.valueOf(RequestTupple.get("CCV")));
						   subReqModel.setExpire(RequestTupple.get("EXPIRE"));
						   subReqModel.setType(RequestTupple.get("TYPE"));
						   subReqModel.setLocation(Integer.valueOf(RequestTupple.get("AREA")));
						   System.out.println("pending pid:::::::::"+Integer.valueOf(RequestTupple.get("PID")));
						   //init unrgisterd customer
						   subCus=new UnregisteredUser(RequestTupple.get("FNAME"),RequestTupple.get("LNAME"),RequestTupple.get("PASSWORD"),RequestTupple.get("PHONE"),RequestTupple.get("EMAIL"),"");
						  
						
						    }	//end for
						  
							PendingRequestDetailsView.setDetailsArea("USER DETAILS::::::::::\n"+subCus.toString()+"\n\nUser Subscription Request:::::::::\n"+subReqModel.toString());
							
							//setbuttons listeners 
							 SetButtons(reqid,subReqModel);
							 
							//display main window
							PendingRequestDetailsView.setVisible(true);	
						}
						else//invoice return
						{
	
							   //back from finance System
							int uid=subReqModel.getUID();
							int invoice=Integer.parseInt(srs.get(0).get("INVOICE_NUMBER"));		
											
							   //insert to customer_orders
							String insertQuery = "adu"	+"INSERT INTO customer_orders "
                                 	                    +"(uid,invoice_number) VALUES "
                                                     	+"(" + uid + "," + invoice + ")";
							
		                    //send mail from finance System + jOptionPane
							  JOptionPane.showMessageDialog(null, "Finance System successfully Has Charged Customer " ,"Finace System Notification", JOptionPane.INFORMATION_MESSAGE);
							String mail=srs.get(0).get("EMAIL");
							String FName=srs.get(0).get("FNAME");
							String LNAME=srs.get(0).get("LNAME"); 
							String Price=srs.get(0).get("PRICE_PAID");
							String Date=srs.get(0).get("TIMESTAMP");
							String Credit=srs.get(0).get("CREDITNUM");
							int serviceID=Integer.parseInt(srs.get(0).get("SERVICE_ID"));
							  System.out.println("invoice::::::"+invoice);
							  System.out.println("service::::::"+serviceID);
							String newCredit=Credit.substring(0,4)+"-"+"XXXX"+"-"+"XXXX"+"-"+Credit.substring(11,15);
							String NewDate=Date.substring(0,Date.length()-5);
							
							 String desc;
							if (serviceID==5)
							 	 desc=subReqModel.getServiceByName(serviceID)+"On Area"+subReqModel.getLocation();
							else
								desc=subReqModel.getServiceByName(serviceID);
							
							String body=" Dear "+LNAME+" "+FName+","+"\n Your Invoice Number : "+invoice+"\nDescription : "+ desc+ "\nCredit Details : "+newCredit+"\n Price :"+ Price+"$" +"\n Date : "+NewDate;
							//send Mail
							SendMail(body,mail);
							
							
							///get curr subscriptions request
							String searchQuery = "search"	+"SELECT sReq.reqid,sReq.uid,u.fname,u.lname "
			                        +" FROM subreq AS sReq, user AS u"
	                                +" WHERE sReq.uid=u.uid AND sReq.isapprovedbycussrvc=0 ";
	                             
							//activate the back button
							PendingRequestDetailsView.clickBackButton();
							
							   
							    sendToServer(insertQuery);
	                         	sendToServer(searchQuery);
						}
						
						
						///set fields GUi	
							
						
						
					}

					@Override
					public void handleNullSearchResult() 
					{
						PendingRequestDetailsView.displayWrnMessage("Request Not Found!!!");
						
					}


	
	
}
